package com.itheima.Service.Impl;

import com.itheima.Mapper.OrderDao;
import com.itheima.Service.OrderService;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.SubmitOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int submitOrder(SubmitOrder submitOrder) {
        //查询验证码是否正确
        if (redisTemplate.opsForValue().get(submitOrder.getTelephone()) == null) {
            throw new RuntimeException("验证码已过期");
        } else if (!redisTemplate.opsForValue().get(submitOrder.getTelephone()).equals(submitOrder.getValidateCode())) {
            throw new RuntimeException("验证码错误");
        }

        //查询当天的预约是否已满
        System.out.println("预约时间"+submitOrder.getOrderDate());
        OrderSetting result=orderDao.selectByDate(submitOrder.getOrderDate());

        if (result.getNumber()==0){
            throw new RuntimeException("不可预约");
        }

        try {
            if(result.getReservations()>result.getNumber()){
                result.setReservations(result.getReservations()+1);
            }
        } catch (Exception e) {
            throw new RuntimeException("预约已满");
        }

        //查询是否注册会员
        Member member= orderDao.selectByPhoneNumber(submitOrder.getTelephone());
        if(member==null){
            member=new Member();
            member.setName(submitOrder.getName());
            member.setSex(submitOrder.getSex());
            member.setPhoneNumber(submitOrder.getTelephone());
            member.setRegTime(submitOrder.getOrderDate());
            orderDao.addMember(member);
        }

        submitOrder.setMemberID(String.valueOf(member.getId()));

        //添加预约
        orderDao.addOrder(submitOrder);

        //查询用户是否在同一天预约了同一个套餐
        Order order=orderDao.selectByMemberIdAndSetmealId(member.getId());



        //获得预约当天的天数
        int day=order.getOrderDate().getDay();

        return day;




    }
}
